package com.lqg.bookLibrary.service.impl;

import com.lqg.bookLibrary.common.core.domain.LoginUser;
import com.lqg.bookLibrary.common.exception.ServiceException;
import com.lqg.bookLibrary.pojo.Users;
import com.lqg.bookLibrary.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class LoginUserServiceImpl implements UserDetailsService {
    @Autowired
    private IUsersService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            if(username == null || "".equals(username)){
            throw new ServiceException("用户名为空");
        }

        Users user = userService.lambdaQuery().eq(Users::getUsername,username).one();

        if (user == null){
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        // 权限
        for(String s : user.getRole().split(" ")){
            s="ROLE_"+s;
            grantedAuthorities.add(new SimpleGrantedAuthority(s));
        }

        return new LoginUser(user.getUsername(),
                user.getPassword(),grantedAuthorities);
    }

}
